package dao

import (
	"go_server/game_server/database/mysql"
	"go_server/game_server/util"
	"go_server/zinx/zlog"
	"gorm.io/datatypes"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type TaskInfo struct {
	RoleId     int64                                 `gorm:"column:role_id"`
	Chapter    int32                                 `gorm:"column:chapter"`
	MainTask   datatypes.JSONType[map[int32][]int32] `gorm:"column:main_task"`
	GrowTask   datatypes.JSONType[map[int32][]int32] `gorm:"column:grow_task"`
	BranchTask datatypes.JSONType[map[int32][]int32] `gorm:"column:branch_task"`
}

func (TaskInfo) TableName() string {
	return "task_info"
}

var (
	all_task_info_field = util.GetGormFields(TaskInfo{})
)

func GetTaskInfoByRoleId(RoleId int64) *TaskInfo {
	db := mysql.GetServerDBConnection()
	var taskInfo TaskInfo
	if err := db.Select(all_task_info_field).Where("role_id=?", RoleId).First(&taskInfo).Error; err != nil {
		if err != gorm.ErrRecordNotFound {
			zlog.Errorf("GetTaskInfoByRoleId ERR!!! RoleId: %s, err: %v", RoleId, err)
		}

		taskInfo = TaskInfo{
			RoleId:     RoleId,
			Chapter:    1,
			MainTask:   datatypes.JSONType[map[int32][]int32]{},
			GrowTask:   datatypes.JSONType[map[int32][]int32]{},
			BranchTask: datatypes.JSONType[map[int32][]int32]{},
		}
	}
	return &taskInfo
}

func UpdateTaskInfoByMainTask(taskInfo TaskInfo, fields []string) {
	if taskInfo.MainTask.Data() == nil {
		mainTask := make(map[int32][]int32)
		taskInfo.MainTask = datatypes.NewJSONType(mainTask)
	}

	if taskInfo.GrowTask.Data() == nil {
		growTask := make(map[int32][]int32)
		taskInfo.GrowTask = datatypes.NewJSONType(growTask)
	}

	if taskInfo.BranchTask.Data() == nil {
		branchTask := make(map[int32][]int32)
		taskInfo.BranchTask = datatypes.NewJSONType(branchTask)
	}

	db := mysql.GetServerDBConnection()

	if err := db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "date_key,role_id"}},
		DoUpdates: clause.AssignmentColumns(fields),
	}).Create(taskInfo).Error; err != nil {
		zlog.Errorf("create or update task_info %v data failed: %v", taskInfo, err)
	}
}
